package com.hhh.bigevent.config;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.hhh.bigevent.utils.JwtUtil;
import com.hhh.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.hasLength(authorization)) {
            if (authorization.equals(redisTemplate.opsForValue().get(authorization))) {
                redisTemplate.expire(authorization, 7, TimeUnit.DAYS);
                try {
                    Map<String, Object> map = JwtUtil.parseToken(authorization);
                    //将用户信息存放到线程中
                    ThreadLocalUtil.set(map);
                    return true;
                } catch (TokenExpiredException e) {
                    // 登录失效返回401
                    response.setStatus(401);
                    return false;
                }
            }
        }
        response.setStatus(401);
        return false;
    }
}
